#!/bin/bash

PSQL="psql --username=freecodecamp --dbname=number_guess -t --no-align -c"
NUMBER=$((RANDOM % 900 + 100))
echo $NUMBER
GUESS_NUMBER=0

echo -e "\nEnter your username:"
read USERNAME

USER=$($PSQL "SELECT * FROM users WHERE name = '$USERNAME'")

if [[ -z $USER ]]
then
  echo -e "\nWelcome, $USERNAME! It looks like this is your first time here."
  INSERT_USERS_RESULT=$($PSQL "INSERT INTO users (name) VALUES('$USERNAME')")
  USER_ID=$($PSQL "SELECT user_id FROM users WHERE name = '$USERNAME'")
else
  USER_ID=$($PSQL "SELECT user_id FROM users WHERE name = '$USERNAME'")
  GAMES_PLAYED=$($PSQL "SELECT COUNT(*) FROM games WHERE user_id = $USER_ID")
  BEST_GAME=$($PSQL "SELECT MIN(guess_number) FROM games WHERE user_id = $USER_ID")
  echo -e "\nWelcome back, $USERNAME! You have played $GAMES_PLAYED games, and your best game took $BEST_GAME guesses."
fi

GUESS() {
  if [[ $1 ]]
  then
    echo -e "\n$1"
  fi

  read USER_NUMBER
  (( GUESS_NUMBER++ ))

  if [[ ! $USER_NUMBER =~ ^[0-9]+$ ]]
  then
    GUESS "That is not an integer, guess again:"
  fi

  if [[ $USER_NUMBER < $NUMBER ]]
  then
    GUESS "It's lower than that, guess again:"
  fi

  if [[ $USER_NUMBER > $NUMBER ]]
  then
    GUESS "It's higher than that, guess again:"
  fi

  INSERT_GAMES_RESULT=$($PSQL "INSERT INTO games (user_id, guess_number) VALUES($USER_ID, $GUESS_NUMBER)")
  if [[ $INSERT_GAMES_RESULT == "INSERT 0 1" ]]
  then
    echo "You guessed it in $GUESS_NUMBER tries. The secret number was $NUMBER. Nice job!"
    exit 0
  else
    exit 0
  fi
}

GUESS "Guess the secret number between 1 and 1000:"
